﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TheVerge.Phone.Controls;
using TheVerge.Base.Models;
using TheVerge.Base;
using TheVerge.Base.Platform;
using System.Windows.Data;
using Microsoft.Phone.Globalization;
using System.Globalization;

namespace TheVerge.Phone.Pages
{
    public partial class SectionsPage : MainPage
    {
        public SectionsPage()
        {
            InitializeComponent();
            DataContext = App.MainVM.Sections;
        }

        protected override MainPage.PageSection Section
        {
            get { return MainPage.PageSection.Sections; }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            App.MainVM.ActivePinnable = App.MainVM.Sections;
        }

        protected override void LoadFromQueryStrings(Dictionary<string, string> queryStrings)
        {
            App.MainVM.ActivePinnable.LoadFromPin(queryStrings);
        }

        private void thePiv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (thePiv.SelectedItem != null)
            {
                var pivItem = thePiv.SelectedItem as PivotItem;
                var vm = pivItem.DataContext as IVMEntries;
                if (vm != null && vm.ItemsCount == 0)
                    vm.Refresh();
            }
        }

        private void Section_Click(object sender, RoutedEventArgs e)
        {
            var fe = sender as FrameworkElement;
            var entries = fe.DataContext as VMEntries<ArticleEntry>;

            App.MainVM.Articles = entries;

            NavigationService.Navigate(new Uri(@"/Pages/ArticlesPage.xaml", UriKind.Relative));
        }
    }

    public class BackgroundColorConverter : IValueConverter
    {
        public Brush HasItemsColor { get; set; }
        public Brush NoItemsColor { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (true.Equals(value))
                return HasItemsColor;
            else
                return NoItemsColor;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class BrandLongListConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                var items = value as IEnumerable<VMBrand>;
                var x = AlphaKeyGroup<VMBrand>.CreateGroups(items, CultureInfo.CurrentCulture, b => b.Name, true);

                return x;
            }
            catch
            {
                return value;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public class AlphaKeyGroup<T> : List<T>
        {
            /// <summary>
            /// The delegate that is used to get the key information.
            /// </summary>
            /// <param name="item">An object of type T</param>
            /// <returns>The key value to use for this object</returns>
            public delegate string GetKeyDelegate(T item);

            /// <summary>
            /// The Key of this group.
            /// </summary>
            public string Key { get; private set; }

            /// <summary>
            /// Public constructor.
            /// </summary>
            /// <param name="key">The key for this group.</param>
            public AlphaKeyGroup(string key)
            {
                Key = key;
            }

            /// <summary>
            /// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
            /// </summary>
            /// <param name="slg">The </param>
            /// <returns>The items source for a LongListSelector</returns>
            private static List<AlphaKeyGroup<T>> CreateGroups(SortedLocaleGrouping slg)
            {
                List<AlphaKeyGroup<T>> list = new List<AlphaKeyGroup<T>>();

                foreach (string key in slg.GroupDisplayNames)
                {
                    list.Add(new AlphaKeyGroup<T>(key));
                }

                return list;
            }

            /// <summary>
            /// Create a list of AlphaGroup<T> with keys set by a SortedLocaleGrouping.
            /// </summary>
            /// <param name="items">The items to place in the groups.</param>
            /// <param name="ci">The CultureInfo to group and sort by.</param>
            /// <param name="getKey">A delegate to get the key from an item.</param>
            /// <param name="sort">Will sort the data if true.</param>
            /// <returns>An items source for a LongListSelector</returns>
            public static List<AlphaKeyGroup<T>> CreateGroups(IEnumerable<T> items, CultureInfo ci, GetKeyDelegate getKey, bool sort)
            {
                SortedLocaleGrouping slg = new SortedLocaleGrouping(ci);
                List<AlphaKeyGroup<T>> list = CreateGroups(slg);

                foreach (T item in items)
                {
                    int index = 0;
                    if (slg.SupportsPhonetics)
                    {
                        //check if your database has yomi string for item
                        //if it does not, then do you want to generate Yomi or ask the user for this item.
                        //index = slg.GetGroupIndex(getKey(Yomiof(item)));
                    }
                    else
                    {
                        index = slg.GetGroupIndex(getKey(item));
                    }
                    if (index >= 0 && index < list.Count)
                    {
                        list[index].Add(item);
                    }
                }

                if (sort)
                {
                    foreach (AlphaKeyGroup<T> group in list)
                    {
                        group.Sort((c0, c1) => { return ci.CompareInfo.Compare(getKey(c0), getKey(c1)); });
                    }
                }

                return list;
            }
        }
    }
}